//
//  NewViewController.m
//  接收端
//
//  Created by apple on 16/4/8.
//  Copyright © 2016年 SherrySorftware. All rights reserved.
//

#import "NewViewController.h"
#import "BluetoothClass.h"
#import <AVFoundation/AVFoundation.h>
#import "AppDelegate.h"
#import <MAMapKit/MAMapKit.h>
#import "RequestServiceForData.h"
#import <AudioToolbox/AudioToolbox.h>
@interface NewViewController ()<bluetoothClassDelegate,MAMapViewDelegate>
{
    MAMapView *_mapView;
}
@property (weak, nonatomic) IBOutlet UILabel *lab_state;
@property (weak, nonatomic) IBOutlet UILabel *lab_message;
@property (weak, nonatomic) IBOutlet UITextView *txv_log;
@property (weak, nonatomic) BluetoothClass *CVBLEOBJ;
@property (strong, nonatomic) AVAudioPlayer *player;

@end

@implementation NewViewController
@synthesize CVBLEOBJ;
- (void)viewDidLoad {
    [super viewDidLoad];
    CVBLEOBJ = [BluetoothClass shareAppDelegate];
    CVBLEOBJ.delegate = self;
    //监听状态
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(findOrConnectDevice:) name:@"CBCentralManagerStatePoweredOn" object:nil];
    
    [MAMapServices sharedServices].apiKey = @"ef4268ffbedb8c6881159b57c43e8e10";
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 150, CGRectGetWidth(self.view.bounds), 100)];
    _mapView.delegate = self;
    //[self.view addSubview:_mapView];
}
///状态更新
- (void)updataConnetionState:(NSString*)state {
    [self.lab_state setText:state];
}
//获取到新数据
- (void)didGetNewData:(NSString*)data {
    [self.lab_message setText:data];

    if ([data hasPrefix:@"喂，妖妖灵吗"]) {
        //声音播放
        NSString *path = [[NSBundle mainBundle] pathForResource:@"mmm" ofType:@"wav"];
        //组装并播放音效
        SystemSoundID soundID;
        NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)filePath, &soundID);
        AudioServicesPlaySystemSound(soundID);
    }else if ([data hasSuffix:@"劳"]){
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"tel://13800138000"]];

        //声音播放
        //NSString *soundPath=[[NSBundle mainBundle] pathForResource:@"iloveyou" ofType:@"mp3"];
        //NSURL *soundUrl=[[NSURL alloc] initFileURLWithPath:soundPath];
        //self.player=[[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
        
        //获取位置发送
        _mapView.showsUserLocation = YES;
       
    }
//    [[AppDelegate shareDelegate].player prepareToPlay];
//    [AppDelegate shareDelegate].player.volume = 80.0;
//    AVAudioSession *audioSession=[AVAudioSession sharedInstance];
//    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
//    [audioSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionAllowBluetooth error:nil];
//    [audioSession setActive:YES error:nil];
//    [[AppDelegate shareDelegate].player play];
    
}

//日志更新
- (void)updataLog:(NSString*)log {
    [self.txv_log setText:[self.txv_log.text stringByAppendingString:[NSString stringWithFormat:@"\n%@",log]]];
}

///确保蓝牙打开的时候连接判断连接或查找设备
- (void)findOrConnectDevice:(id)sender {
    NSUserDefaults *defaults = [[NSUserDefaults alloc]init];
    NSString *identifier = [defaults valueForKey:@"identifier"];
    if (identifier.length) {
        NSArray *arr = @[identifier];
        NSArray *deviceList = [CVBLEOBJ findDidConnectDivice:arr];
        if (deviceList.count>0) {
            CBPeripheral *tempPeripheral = [deviceList lastObject];
            [CVBLEOBJ connetDevice:tempPeripheral];
        }else {
            [CVBLEOBJ findDiviceNearMe];
        }
    }else {
        [CVBLEOBJ findDiviceNearMe];
    }
}

-(void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation
updatingLocation:(BOOL)updatingLocation
{
    if(updatingLocation)
    {
        _mapView.showsUserLocation = NO;
        //取出当前位置的坐标
        NSLog(@"latitude : %f,longitude: %f",userLocation.coordinate.latitude,userLocation.coordinate.longitude);
        // 依次获取CLLocation中封装的经度、纬度、高度、速度、方向等信息
        self.txv_log.text = [NSString stringWithFormat:@"lat=%g,",userLocation.location.coordinate.latitude];
        self.txv_log.text = [self.txv_log.text stringByAppendingString:[NSString stringWithFormat:@"lon=%g",userLocation.location.coordinate.longitude]];
        self.txv_log.text = [self.txv_log.text stringByAppendingString:[NSString stringWithFormat:@"%g",userLocation.location.altitude]];
        self.txv_log.text = [self.txv_log.text stringByAppendingString:[NSString stringWithFormat:@"%g",userLocation.location.speed]];
        self.txv_log.text = [self.txv_log.text stringByAppendingString:[NSString stringWithFormat:@"%g",userLocation.location.course]];
        NSLog(@"%@",self.txv_log.text);
        
        //发送点
        [[RequestServiceForData requestOnly] postLocationString:self.txv_log.text device:@"问题天天都多" passData:^(NSDictionary *dict) {
            [self.txv_log setText:@"发送成功，执行震动"];
            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        }];
    }
}

// 成功获取定位数据后将会激发该方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    // 获取最后一个定位数据
    CLLocation* location = [locations lastObject];
    // 依次获取CLLocation中封装的经度、纬度、高度、速度、方向等信息
    self.txv_log.text = [NSString stringWithFormat:@"%g",location.coordinate.latitude];
    self.txv_log.text = [self.txv_log.text stringByAppendingString:[NSString stringWithFormat:@"%g",location.coordinate.longitude]];
    self.txv_log.text = [self.txv_log.text stringByAppendingString:[NSString stringWithFormat:@"%g",location.altitude]];
    self.txv_log.text = [self.txv_log.text stringByAppendingString:[NSString stringWithFormat:@"%g",location.speed]];
    self.txv_log.text = [self.txv_log.text stringByAppendingString:[NSString stringWithFormat:@"%g",location.course]];
    NSLog(@"%@",self.txv_log.text);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
